package com.rpoonolly.simplegame.animation;

import java.util.List;

import javax.vecmath.Vector2d;

import com.rpoonolly.simplegame.core.aabb.AABBEntity;
import com.rpoonolly.simplegame.core.aabb.EntityGameMap;
import com.rpoonolly.simplegame.textures.TextureFileDescriptor;
import com.rpoonolly.simplegame.textures.TextureId;

public class SimpleNPCAnimator extends AnimationProcessor<AABBEntity, CharacterAnimation> {
	public SimpleNPCAnimator(EntityGameMap<AABBEntity> gameMap, 
			TextureFileDescriptor animationMap, List<String> groupsToAnimate) {
		super(gameMap, animationMap, groupsToAnimate);
	}
	
	@Override
	protected void loadAnimationCycles() {
		TextureId[] animationCycle;
		CharacterAnimation[] actionsToMap = {
			CharacterAnimation.WALK_UP,
			CharacterAnimation.WALK_LEFT,
			CharacterAnimation.WALK_DOWN,
			CharacterAnimation.WALK_RIGHT
		};

		for(int j = 0; j < actionsToMap.length; j++) {
			animationCycle = new TextureId[animationMap.mapWidth];
			for(int i = 0; i < animationMap.mapWidth; i++)
					animationCycle[i] = new TextureId(animationMap, i, j);
			animations.put(actionsToMap[j], animationCycle);
		}
		
		lastAnimation = CharacterAnimation.WALK_DOWN;
	}
	
	@Override
	protected void processAnimationFrame(AABBEntity entity) {
		TexturedDynamicEntity character = (TexturedDynamicEntity) entity;
		Vector2d v = character.getDirection();
		TextureId newAnimFrame;
		
		if (v.x == 0 && v.y == 0) {
			newAnimFrame = getAnimationFrame(lastAnimation);
		} else if (Math.abs(v.x) > Math.abs(v.y)) {
			if (v.x > 0)
				newAnimFrame = getAnimationFrame(CharacterAnimation.WALK_RIGHT);
			else
				newAnimFrame = getAnimationFrame(CharacterAnimation.WALK_LEFT);
		} else {
			if (v.y > 0)
				newAnimFrame = getAnimationFrame(CharacterAnimation.WALK_UP);
			else
				newAnimFrame = getAnimationFrame(CharacterAnimation.WALK_DOWN);
		}
		
		character.setCurrentTexture(newAnimFrame);
	}
}
